//
//  user_editController.m
//  SoundPill
//
//  Created by 宋鹏鹏 on 15/4/13.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "user_editController.h"
#import "set_nameitem.h"
#import "edit_lineItem.h"
#import "set_nolineItem.h"
#import "editNameController.h"

#import "LoginViewController.h"
#import "imageVPickController.h"
#import "UIImageView+WebCache.h"
//上传
#import "QiniuSDK.h"
#import "AFNetworking.h"
#import "JSONKit.h"

#import "JCAlertView.h"
#import "UIViewExt.h"
#import "LCActionSheet.h"
@interface user_editController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIAlertViewDelegate>
{
    //修改头像
    set_nameitem *_editHead;
    //用户名
    edit_lineItem *_userName;
    //性别
    edit_lineItem *_userSex;
    NSString *initsex;
    //所在地
    edit_lineItem *_userLocation;
    NSString *initlocation;
    //简介
    set_nolineItem *_simpleIntroduce;
    
    UIButton *_lastSelect;
    UIPickerView *locatiaonView;
    //pickView data
    NSArray *pickViewData;
    UIView *view1;
    UIView *view2;
    NSString *_provincesString;
    NSString *_cityString;
    
    //////用户头像路径
    NSString *headImageFilePath;
    NSString *nameFilePath;
    NSString *userSex;
    NSString *locationFilePath;

    /*上传*/
    NSString *token;
    
    //
    UIButton *cancelBtn;
    UIButton *sureBtn;
    //
    UIButton *sexCancelBtn;
    UIButton *sexSureBtn;
    
    //
    UIView *grayBackGround;
    //
    UIPickerView *sexPickView;
    NSArray *sexData;

}
@end

@implementation user_editController
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
        
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        [back setFrame:CGRectMake(0, 0, 30, 30)];
        [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
        [back addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
        self.navigationItem.leftBarButtonItem = backItem;
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0) {
        
        self.edgesForExtendedLayout=UIRectEdgeNone;
        
    }
    
    sexData = [[NSArray alloc] initWithObjects:@"男",@"女",@"外星人",nil];
    self.title=@"编辑资料";
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc]init];
    backItem.title=@"取消";
    self.navigationItem.backBarButtonItem = backItem;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //修改头像
    _editHead = [[set_nameitem alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 44)];
    //_editHead.headImage.image=[UIImage imageNamed:@"login"];
  
    //[_setNameItem.headImage setImageWithURL:[NSURL URLWithString:self.focustabViewModel.image1URL]];
    _editHead.title = @"头像";
//    [_editHead setBackgroundImage:[UIImage imageNamed:@"head_bacground"] forState:UIControlStateHighlighted];
    
    [self.view addSubview:_editHead];
    [_editHead addTarget:self action:@selector(editHeadClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    //用户名
    _userName = [[edit_lineItem alloc]initWithFrame:CGRectMake(0, 44, self.view.width, 44)];
    _userName.title = @"用户名";
    //_userName.textLabel.text = @"犀牛哥要peace";
//    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
//    //读取字典类型NSDictionary类型的数据
//    NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
//    NSString *name =[myDictionary objectForKey:@"username"];
//    _userName.textLabel.text = name;
    
//    [_userName setBackgroundImage:[UIImage imageNamed:@"head_bacground"] forState:UIControlStateHighlighted];

    
    [self.view addSubview:_userName];
    //
    [_userName addTarget:self action:@selector(userNameEditClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    //性别
    _userSex = [[edit_lineItem alloc]initWithFrame:CGRectMake(0, 2*44, self.view.width, 44)];
    _userSex.title = @"性别";
    //_userSex.textLabel.text = @"男/女/外星人";
//     [_userSex setBackgroundImage:[UIImage imageNamed:@"head_bacground"] forState:UIControlStateHighlighted];
    
//    NSString *sex =[myDictionary objectForKey:@"sex"];
//    _userSex.textLabel.text = sex;
    
    [self.view addSubview:_userSex];
    //
    [_userSex addTarget:self action:@selector(userSexClick) forControlEvents:UIControlEventTouchUpInside];
    
    //所在地
    _userLocation = [[edit_lineItem alloc]initWithFrame:CGRectMake(0, 3*44, self.view.width, 44)];
    _userLocation.title = @"所在地";
    //以前储存的（网络的）
    //_userLocation.textLabel.text = @"北京市 东城区";
    
//    NSString *location =[myDictionary objectForKey:@"location"];
//    _userLocation.textLabel.text = location;
    [self.view addSubview:_userLocation];
    
    
//     [_userLocation setBackgroundImage:[UIImage imageNamed:@"head_bacground"] forState:UIControlStateHighlighted];
    //
    [_userLocation addTarget:self action:@selector(userLocationClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    grayBackGround = [[UIView alloc]initWithFrame:CGRectMake(0, 5.5*44, self.view.width, self.view.height*0.5)];
    grayBackGround.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"lightgray_s"]];
    [self.view addSubview:grayBackGround];
    grayBackGround.alpha = 0;
    


    
    //简介
    _simpleIntroduce = [[set_nolineItem alloc]initWithFrame:CGRectMake(0, 4*44, self.view.width, 44)];
    _simpleIntroduce.title = @"个人签名";
    _simpleIntroduce.textLabel.text = [[NSUserDefaults standardUserDefaults] valueForKey:@"introduce"];
    //读本地简介
    
    [self.view addSubview:_simpleIntroduce];
//    [_simpleIntroduce setBackgroundImage:[UIImage imageNamed:@"head_bacground"] forState:UIControlStateSelected];
    //
    [_simpleIntroduce addTarget:self action:@selector(simpleIntroduceClick) forControlEvents:UIControlEventTouchUpInside];
    
    [self loadItemData];
}
- (void)loadItemData
{
    //头像
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    headImageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:headImageFilePath];//读取图片文件

    

    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取字典类型NSDictionary类型的数据
    NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
    NSString *name =[myDictionary objectForKey:@"username"];
    _userName.textLabel.text = name;
    if ([[myDictionary valueForKey:@"avatar"] isKindOfClass:[NSNull class]]) {
        _editHead.headImage.image = selfPhoto;
    } else {
        [_editHead.headImage setImageWithURL:[NSURL URLWithString:[myDictionary valueForKey:@"avatar"]]];
    }
    
    initsex =[myDictionary objectForKey:@"sex"];
    
    if([initsex isEqualToString:@"1"]){
        initsex=@"男";
    }else if ([initsex isEqualToString:@"2"]){
        initsex=@"女";
    }else if ([initsex isEqualToString:@"0"]){
        initsex=@"外星人";
    }

    _userSex.textLabel.text = initsex;
    
    initlocation =[myDictionary objectForKey:@"location"];
    _userLocation.textLabel.text = initlocation;
    if ( [_userLocation.textLabel.text isEqualToString:@""]) {
        _userLocation.textLabel.text = @"未设置";
    }
    if ( _editHead.headImage.image == nil) {
        _editHead.headImage.image = [UIImage imageNamed:@"default_head"];
    }
    
//    //简介
//    NSString *produce =[myDictionary objectForKey:@"introduce"];
//    _simpleIntroduce.textLabel.text = produce;
    
}
//
- (void)editHeadClick
{
    if (locatiaonView!=nil) {
        [self cancelClick];
    }
    

    _lastSelect.selected = NO;
    _editHead.selected = YES;
    _lastSelect = _editHead;
    
    //
    [self takePictureClick:_editHead];

}
//
- (void)userNameEditClick
{
    if (locatiaonView!=nil) {
        [self cancelClick];
    }
    _lastSelect.selected = NO;
    _userName.selected = YES;
    _lastSelect = _userName;
    
    editNameController *editNameVC = [[editNameController alloc]init];
    [self.navigationController pushViewController:editNameVC animated:YES];
}
- (void)simpleIntroduceClick
{
    editIntroduceController *editIntroduce = [[editIntroduceController alloc] init];
    [self.navigationController pushViewController:editIntroduce animated:YES];
}
#pragma mark - 设置性别
- (void)userSexClick
{
    
    if (locatiaonView!=nil) {
        [self cancelClick];
    }
    self.tabBarController.tabBar.hidden=YES;
    _lastSelect.selected = NO;
    _userSex.selected = YES;
    _lastSelect = _userSex;
    grayBackGround.alpha =1;

//    editSexController *sexVC = [[editSexController alloc]init];
//    [self.navigationController pushViewController:sexVC animated:YES];
    
    if (sexPickView==nil) {
    //显示选择性别的滚动轴
    //
    sexPickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 20, self.view.width,self.view.height*0.45)];
    sexPickView.backgroundColor = [UIColor clearColor];
    
    sexPickView.tag = 100001;
    sexPickView.delegate = self;
    sexPickView.dataSource = self;
    
    //第二种
    // NSString *path = [[NSBundle mainBundle]pathForResource:@"city" ofType:@"plist"];
    //pickViewData = [[NSArray alloc] initWithContentsOfFile:path];
    
    [grayBackGround addSubview:sexPickView];
    

    sexCancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.03, 10, self.view.width*0.25, 30)];
    sexCancelBtn.backgroundColor = [UIColor clearColor];
    [sexCancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [sexCancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sexCancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [sexCancelBtn addTarget:self action:@selector(sexCancelClick) forControlEvents:UIControlEventTouchUpInside];
    
    [grayBackGround addSubview:sexCancelBtn];
    
    
    sexSureBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.72, 5, self.view.width*0.25, 30)];
    sexSureBtn.backgroundColor = [UIColor clearColor];
    [sexSureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sexSureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [sexSureBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [sexSureBtn addTarget:self action:@selector(sexSureClick) forControlEvents:UIControlEventTouchUpInside];
    [grayBackGround addSubview:sexSureBtn];
         
    }

    //
    _userSex.textLabel.text = @"男";
 
    
}
- (void)sexCancelClick
{
    
   self.tabBarController.tabBar.hidden=NO;
    _userSex.textLabel.text = initsex;
//    [self loadItemData];
    sexPickView.alpha = 0;
    sexPickView = nil;
    [sexPickView removeFromSuperview];
    [sexCancelBtn removeFromSuperview];
    [sexSureBtn removeFromSuperview];
    grayBackGround.alpha = 0;

}
- (void)sexSureClick
{
    if (_userSex.textLabel.text!=nil) {
        initsex = _userSex.textLabel.text;
        [self postUserSex:_userSex.textLabel.text];
    }
}
#pragma mark------传Sex
- (void)postUserSex:(NSString *)sex
{
//    NSLog(@"Sex 是%@",sex);
    NSString *sexvn = sex;
    
    if ([sexvn isEqualToString:@"男"]) {
        sexvn = @"1";
    }else if ([sex isEqualToString:@"女"]) {
        sexvn = @"2";
    }else if ([sex isEqualToString:@"外星人"]) {
        sexvn = @"0";
    }
    
    //
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:sexvn forKey:@"sex"];
    [dataDic setObject:uid forKey:@"user"];
    
    //NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",self.listdataModel.CinemeID];
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
//    NSLog(@"%@",str);
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:sex forKey:@"sex"];
        myDictionary = dic;
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        //        NSLog(@"%@",myDictionary);
        [userDefaultes synchronize];
        
        
        [sexPickView removeFromSuperview];
        sexPickView =nil;
        [sexCancelBtn removeFromSuperview];
        [sexSureBtn removeFromSuperview];
        grayBackGround.alpha = 0;
        self.tabBarController.tabBar.hidden=NO;
        _lastSelect.selected = NO;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            //在别的地方登录，token过期，需重新登录
            
            // 加载主视图控制器
            LoginViewController *login = [[LoginViewController alloc] init];
            self.view.window.rootViewController = login;
            
        }else {
            [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }

    }];
}

//
- (void)userLocationClick
{
    //取消性别设置
    [self sexCancelClick];
     self.tabBarController.tabBar.hidden=YES;
    
    _lastSelect.selected = NO;
    _userLocation.selected = YES;
    _lastSelect = _userLocation;
    grayBackGround.alpha = 1;

    if (locatiaonView ==nil) {
        
        locatiaonView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 20, self.view.width,self.view.height*0.45)];
        locatiaonView.backgroundColor = [UIColor clearColor];
        locatiaonView.tag =100000;
        
        locatiaonView.delegate = self;
        locatiaonView.dataSource = self;
        
        //第二种
        NSString *path = [[NSBundle mainBundle]pathForResource:@"city" ofType:@"plist"];
        pickViewData = [[NSArray alloc] initWithContentsOfFile:path];
        
    
        //
        [grayBackGround addSubview:locatiaonView];
        
        cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.03, 10, self.view.width*0.25, 30)];
        cancelBtn.backgroundColor = [UIColor clearColor];
        [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [cancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [cancelBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
        
        [grayBackGround addSubview:cancelBtn];
        
        
        sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.width*0.72, 10, self.view.width*0.25, 30)];
        sureBtn.backgroundColor = [UIColor clearColor];
        [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [sureBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [sureBtn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
        [grayBackGround addSubview:sureBtn];

    }
     _userLocation.textLabel.text = @"北京 东城区";
    
}
#pragma mark - 按钮事件
- (void)cancelClick
{
    self.tabBarController.tabBar.hidden=NO;
//    [self loadItemData];
    _userLocation.textLabel.text = initlocation;
    locatiaonView.alpha = 0;
    locatiaonView = nil;
    [locatiaonView removeFromSuperview];
    [cancelBtn removeFromSuperview];
    [sureBtn removeFromSuperview];
    grayBackGround.alpha = 0;
}
- (void)sureClick
{
    if (_userLocation.textLabel.text!=nil) {
        initlocation = _userLocation.textLabel.text;
        [self postUserLocation:_userLocation.textLabel.text];
    }
    
}
#pragma mark - 设置简介
//- (void)simpleIntroduceClick
//{
//    if (locatiaonView!=nil) {
//        [self cancelClick];
//    }
//    _lastSelect.selected = NO;
//    _simpleIntroduce.selected = YES;
//    _lastSelect = _simpleIntroduce;
//    
//    editIntroduceController *introduceVc = [[editIntroduceController alloc]init];
//    [self.navigationController pushViewController:introduceVc animated:YES];
//
//}
#pragma mark - UIPickerView delegate
//返回有列数 Component列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    
    if (pickerView == sexPickView ) {
        return 1;
    }else
    return 2;
    
}

//返回每一列中的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (pickerView == sexPickView) {
        return sexData.count;
    }else{
    
    //return 10;
    
    if (component == 0) {//第一列
        return pickViewData.count;
    }
    
    //返回第一列选择的行的索引
    NSInteger selectedRow = [pickerView selectedRowInComponent:0];
    //取得省级字典
    NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
    //取得该省下所有的市
    NSArray *cities = [items objectForKey:@"cities"];
    
        return cities.count;
    }
    
}

//返回每个item中的title  实际上返回的就是一个label
- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component {
    if (pickerView == sexPickView){
        NSString *state = sexData[row];
        return state;
    }else{
    
    
    if (component == 0) {//第一列
        NSDictionary *dic = [pickViewData objectAtIndex:row];
        NSString *state = [dic objectForKey:@"state"];
        return state;
    }
    
    //返回第一列选择的行的索引
    NSInteger selectedRow = [pickerView selectedRowInComponent:0];
    //取得省级字典
    NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
    //取得该省下所有的市
    NSArray *cities = [items objectForKey:@"cities"];
    NSString *cityName = [cities objectAtIndex:row];
    return cityName;
    }
    return nil;
}

//选择行的事件
- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row
       inComponent:(NSInteger)component {
    
    if (pickerView == sexPickView) {
        NSString *cityName1 = sexData[row];
        if (cityName1!=nil) {
            _userSex.textLabel.text = cityName1;
             
        }

    }else{
    
    if (component == 0) {
        //刷新指定列中的行
        [pickerView reloadComponent:1];
        //选择指定的item
        [pickerView selectRow:0 inComponent:1 animated:YES];
        //
        NSDictionary *dic = [pickViewData objectAtIndex:row];
        NSString *state = [dic objectForKey:@"state"];
        _provincesString = state;
        
        //返回第一列选择的行的索引
        NSInteger selectedRow = [pickerView selectedRowInComponent:0];
        //取得省级字典
        NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
        //取得该省下所有的市
        NSArray *cities = [items objectForKey:@"cities"];
        
            NSString *cityName1 = [cities objectAtIndex:0];
            _cityString = cityName1;
        
    } else if (component == 1) {
        
        if (_provincesString==nil) {
            NSDictionary *dic = [pickViewData objectAtIndex:0];
            NSString *state = [dic objectForKey:@"state"];
            _provincesString = state;
        }
       
        
        //
        //返回第一列选择的行的索引
        NSInteger selectedRow = [pickerView selectedRowInComponent:0];
        //取得省级字典
        NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
        //取得该省下所有的市
        NSArray *cities = [items objectForKey:@"cities"];
       
        NSString *cityName1 = [cities objectAtIndex:row];
        _cityString = cityName1;
        
    }
    _userLocation.textLabel.text = [NSString stringWithFormat:@"%@ %@",_provincesString,_cityString];
    }
}
//选中第一行

////设置列的宽度
//- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
//    if (component == 0) {
//        return 200;
//    }
//    return 100;
//}

//自定义行中显示的view
- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {
    
    if (pickerView == sexPickView) {
        view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        
        NSString *state = sexData[row];
        label.text=state;
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment=NSTextAlignmentCenter;
        [view addSubview:label];
        
        view.backgroundColor = [UIColor clearColor];
        return view;

    }else{
    
    if (component == 0) {
        view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        NSDictionary *dic = [pickViewData objectAtIndex:row];
        NSString *state = [dic objectForKey:@"state"];
        label.text=state;
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment=NSTextAlignmentCenter;
        [view1 addSubview:label];
        
        view1.backgroundColor = [UIColor clearColor];
        return view1;
    }else if(component == 1){
        
        view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
        //返回第一列选择的行的索引
        NSInteger selectedRow = [pickerView selectedRowInComponent:0];
        //取得省级字典
        NSDictionary *items = [pickViewData objectAtIndex:selectedRow];
        //取得该省下所有的市
        NSArray *cities = [items objectForKey:@"cities"];
        if (row<cities.count) {
            NSString *cityName1 = [cities objectAtIndex:row];
            
            label.text=cityName1;
        }
        
        label.textColor = [UIColor blackColor];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment=NSTextAlignmentCenter;
        [view2 addSubview:label];
        
        view2.backgroundColor = [UIColor clearColor];
        
        return view2;
    }
    }
    return nil;
}



//弹出actionsheet。选择获取头像的方式
//从相册获取图片
-(void)takePictureClick:(UIButton *)sender
{
    //    /*注：使用，需要实现以下协议：UIImagePickerControllerDelegate,
    //     UINavigationControllerDelegate
    //     */
    //    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    //    //设置图片源(相簿)
    //    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //    //设置代理
    //    picker.delegate = self;
    //    //设置可以编辑
    //    picker.allowsEditing = YES;
    //    //打开拾取器界面
    //    [self presentViewController:picker animated:YES completion:nil];
    LCActionSheet *actionSheet = [LCActionSheet sheetWithTitle:@"请选择图片来源" buttonTitles:@[@"拍照",@"相册"] redButtonIndex:-1 clicked:^(NSInteger buttonIndex) {
        switch (buttonIndex) {
            case 0://照相机
            {
                imageVPickController *imagePicker = [[imageVPickController alloc] init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = YES;
                imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePicker animated:YES completion:nil];
            }
                break;
            case 1://本地相簿
            {
                imageVPickController *imagePicker = [[imageVPickController alloc] init];
                imagePicker.delegate = self;
                imagePicker.allowsEditing = YES;
                imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                // [self presentModalViewController:imagePicker animated:YES];
                [self presentViewController:imagePicker animated:YES completion:nil];
            }
                break;
        }
    }];
    [actionSheet show];
}
#pragma mark -
#pragma UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    NSLog(@"buttonIndex = [%d]",buttonIndex);
    
}
#pragma mark -
#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        _editHead.headImage.image = img;
    [self saveImage:img];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changMyselfAvatar" object:img];
//        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    
    [self performSelector:@selector(getToken) withObject:nil afterDelay:0.7];
    
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)saveImage:(UIImage *)image {
//        NSLog(@"保存头像！");
    //    [userPhotoButton setImage:image forState:UIControlStateNormal];
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    headImageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
//    NSLog(@"imageFile->>%@",headImageFilePath);
    success = [fileManager fileExistsAtPath:headImageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:headImageFilePath error:&error];
    }
    //    UIImage *smallImage=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80
//    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(170, 170)];
    [UIImageJPEGRepresentation(image, 1.0f) writeToFile:headImageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:headImageFilePath];//读取图片文件
    //    [userPhotoButton setImage:selfPhoto forState:UIControlStateNormal];
    //self.img.image = selfPhoto;
    _editHead.headImage.image = selfPhoto;
}

// 改变图像的尺寸，方便上传服务器
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
{
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
//2.保持原来的长宽比，生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

//显示圆形头像
//- (void)xianshiyuantu
//{
//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSString *documentsDirectory = [paths objectAtIndex:0];
//NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
//NSLog(@"imageFile->>%@",imageFilePath);
//UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//
//self.img.image = selfPhoto;
//[self.img.layer setCornerRadius:CGRectGetHeight([self.img bounds]) / 2];  //修改半径，实现头像的圆形化
//self.img.layer.masksToBounds = YES;
//}

#pragma mark -
#pragma mark 上传
- (void)getToken{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:@"1" forKey:@"type"];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
//    NSLog(@"%@",header);
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager GET:@"http://123.57.1.143/api/uptoken?type=3" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = responseObject;
        token = [dic objectForKey:@"token"];
        [self putHeadFileToQN:headImageFilePath];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)putHeadFileToQN:(NSString *)headImagePath{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    
    NSMutableDictionary *optionDic = [NSMutableDictionary dictionary];
    [optionDic setObject:@"3" forKey:@"x:type"];
    [optionDic setObject:uid forKey:@"x:uid"];
//    NSLog(@"===%@",uid);
    QNUploadOption *option = [[QNUploadOption alloc] initWithMime:nil progressHandler:nil params:optionDic checkCrc:NO cancellationSignal:nil];
    
    QNUploadManager *manager = [[QNUploadManager alloc] init];
//    NSLog(@"-------%@",headImagePath);
    [manager putFile:headImagePath key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
//        NSLog(@"info:%@", info.error);
//        NSLog(@"resp:%@", resp);
        
        if (resp == nil) {
            NSLog(@"上传失败");
        } else {
//            AudioUploadState *state = [AudioUploadState sharedInstance];
//            state.uploadId = [resp valueForKey:@"uploadId"];
//            state.url = [resp valueForKey:@"url"];
//            state.state = @"success";
            NSLog(@"上传成功");
            [self postHeadImage:[resp objectForKey:@"url"]];
        }
    } option:option];
}
#pragma mark------传头像uploadId
- (void)postHeadImage:(NSString *)uploadId
{
//    NSLog(@"uploedId 是%@",uploadId);
    
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];

    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:uploadId forKey:@"avatar"];
    [dataDic setObject:uid forKey:@"user"];
    
        //NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",self.listdataModel.CinemeID];
     NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        _lastSelect.selected = NO;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            //在别的地方登录，token过期，需重新登录
            
            // 加载主视图控制器
            LoginViewController *login = [[LoginViewController alloc] init];
            self.view.window.rootViewController = login;
            
        }else {
            [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    }];

    
    
}
#pragma mark------传location
- (void)postUserLocation:(NSString *)location
{
//    NSLog(@"UserLocation 是%@",location);
    //NSString *str2 = [location stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    //发请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
//    NSLog(@"++++++%@",uid);
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:location forKey:@"location"];
    [dataDic setObject:uid forKey:@"user"];
    
    //NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",self.listdataModel.CinemeID];
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:location forKey:@"location"];
        myDictionary = dic;
        
        //存储时，除NSNumber类型使用对应的类型意外，其他的都是使用setObject:forKey:
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        
        //        NSLog(@"%@",myDictionary);
        [userDefaultes synchronize];
        
        
        [locatiaonView removeFromSuperview];
        locatiaonView = nil;
        [cancelBtn removeFromSuperview];
        [sureBtn removeFromSuperview];
        grayBackGround.alpha = 0;
        self.tabBarController.tabBar.hidden=NO;
        _lastSelect.selected = NO;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
        NSInteger statusCode = response.statusCode;
        if (statusCode == 401) {
            //在别的地方登录，token过期，需重新登录
            
            // 加载主视图控制器
            LoginViewController *login = [[LoginViewController alloc] init];
            self.view.window.rootViewController = login;
            
        }else {
            [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType: JCAlertViewButtonTypeDefault ButtonTitle:@"确定" Click:^{
                
            }];
        }
    }];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (alertView.tag ==100003) {
        if (buttonIndex == 0) {
            
        }else if (buttonIndex == 1){
            
            [self sexSureClick];
        }
    }else{

    if (buttonIndex == 0) {
        
    }else if (buttonIndex == 1){
        
        [self sureClick];
        
    }
    }
    
}
- (void)backTo
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    _simpleIntroduce.textLabel.text = [[[NSUserDefaults standardUserDefaults] valueForKey:@"myDictionary"] valueForKey:@"introduce"];
    _userName.textLabel.text = [[[NSUserDefaults standardUserDefaults] valueForKey:@"myDictionary"] valueForKey:@"username"];
//    [self performSelector:@selector(loadItemData) withObject:nil afterDelay:0.5];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
